package com.example.victory.service;

import com.example.victory.entity.companyEntity.CustomerPageEntity;
import com.example.victory.entity.companyEntity.DepOverviewEntity;
import com.example.victory.mapper.CustomerMapper;
import com.example.victory.swagger.handler.MiniAppSalesDepartmentListApiDelegate;
import com.example.victory.swagger.model.*;
import com.example.victory.utils.CrmUtils;
import com.cgws.fintech.sdk.api.mvp.model.ApiRequestCustomerQueryData;
import com.cgws.fintech.sdk.api.mvp.model.CustomerAccount;
import com.cgws.fintech.sdk.common.exception.GlobalException;
import com.cgws.fintech.sdk.common.utils.MoneyHelper;
import com.example.victory.common.web.ServiceHelper;
import com.cgws.fintech.sdk.inner.utils.web.SessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class MiniappSalesDepCustListService implements MiniAppSalesDepartmentListApiDelegate {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private MvpLoginService mvpLoginService;
    @Autowired
    private SessionService sessionService;


    @Override
    public ResponseEntity<ApiResponseDepOverview> getDepOverview() {
        // 获取ryid
        Integer ryid = CrmUtils.getCustomerAccount(sessionService.getCurrentUserSession(true).getUser());
        DepOverviewEntity depOverviewEntity = customerMapper.getDepOverview(ryid);

        ApiResponseDepOverviewData overviewData = new ApiResponseDepOverviewData();
        overviewData.setCustomerCount(depOverviewEntity.getCustomerCount());
        overviewData.setAssetTotal(MoneyHelper.formatMoney(new BigDecimal(depOverviewEntity.getAssetTotal())));

        return ResponseEntity.ok(new ApiResponseDepOverview().data(overviewData));
    }

    /**
     * 获取营业部客户列表
     *
     * @param param 请求参数
     * @return 请求结果
     */
    @Override
    public ResponseEntity<ApiResponseCustomers> getSalesDepartCustList(ApiRequestCustomersPage param) {
        ApiRequestCustomersPageData data = param.getData();
        ServiceHelper.checkDataNotNull(data, "data");

        // 获取ryid
        Integer ryid = CrmUtils.getCustomerAccount(sessionService.getCurrentUserSession(true).getUser());
//        Integer ryid = 1000486;
        List<CustomerPageEntity> customerEntities = customerMapper.getCustomersPage(true, ryid, param.getData());

        List<CustomerResp> custInfoList = new ArrayList<>();
        if(customerEntities == null||customerEntities.size() == 0){
            return ResponseEntity.ok(new ApiResponseCustomers().data(new ApiResponseCustomersData().items(custInfoList)));
        }

        List<ApiRequestCustomerQueryData> customerQueryDataList=new ArrayList<>();
        customerEntities.forEach(customerEntity -> {
            ApiRequestCustomerQueryData customerQueryData=new ApiRequestCustomerQueryData();
            customerQueryData.setCustNum(customerEntity.getCustomerId());
            customerQueryDataList.add(customerQueryData);

            CustomerResp customerResp=new CustomerResp();
            customerResp.setCustomerId(customerEntity.getCustomerId());
            customerResp.setName(customerEntity.getName());
            customerResp.setId(customerEntity.getId());
            customerResp.setPhone(customerEntity.getPhone());
            customerResp.setRiskLevel(StringUtils.isEmpty(customerEntity.getRiskLevel())?null:customerEntity.getRiskLevel());
            customerResp.setCustomerLevel(customerEntity.getCustomerLevel());
            customerResp.setIsActive(customerEntity.getIsActive());

            List<CustomerRespNameValue> customerRespNameValueLists=new ArrayList<>();
            CustomerRespNameValue total=new CustomerRespNameValue();
            total.setName("总资产");
            total.setValue(MoneyHelper.formatMoney(new BigDecimal(customerEntity.getTotal().trim())));
            customerRespNameValueLists.add(total);

            CustomerRespNameValue turnoverRate=new CustomerRespNameValue();
            turnoverRate.setName("周转率");
            turnoverRate.setValue(customerEntity.getTurnoverRate().trim().equals("0.00")?"0":customerEntity.getTurnoverRate().trim());
            customerRespNameValueLists.add(turnoverRate);

            CustomerRespNameValue totalMarket=new CustomerRespNameValue();
            totalMarket.setName("总市值");
            totalMarket.setValue(MoneyHelper.formatMoney(new BigDecimal(customerEntity.getTotalMarket().trim())));
            customerRespNameValueLists.add(totalMarket);

            CustomerRespNameValue commissionAndRate=new CustomerRespNameValue();
            commissionAndRate.setName("佣金");
            commissionAndRate.setValue(MoneyHelper.formatMoney(new BigDecimal(customerEntity.getCommission().trim()))+(customerEntity.getCommissionRate().trim().equals("0.00")?"(0‰)":"("+customerEntity.getCommissionRate().trim()+"‰)"));
            customerRespNameValueLists.add(commissionAndRate);

            CustomerRespNameValue availableTotal=new CustomerRespNameValue();
            availableTotal.setName("可用资产");
            availableTotal.setValue(MoneyHelper.formatMoney(new BigDecimal(customerEntity.getAvailableTotal().trim())));
            customerRespNameValueLists.add(availableTotal);

            CustomerRespNameValue openDate=new CustomerRespNameValue();
            openDate.setName("开户日期");
            openDate.setValue(customerEntity.getOpenDate());
            customerRespNameValueLists.add(openDate);

            customerResp.setNameValue(customerRespNameValueLists);
            custInfoList.add(customerResp);
        });

        if(customerQueryDataList.size()>0){
            List<CustomerAccount> customerAccountList = CrmUtils.getCustAccountListByIds(mvpLoginService, customerQueryDataList);
            if (customerAccountList != null) {
                custInfoList.forEach(customer -> {
                    customerAccountList.forEach(customerAccount->{
                        if(!StringUtils.isEmpty(customerAccount.getFcid())&&customer.getCustomerId().equals(customerAccount.getCustNum())){
                            customer.setImId(customerAccount.getFcid());
                        }
                    });
                });
            }
        }
        return ResponseEntity.ok(new ApiResponseCustomers().data(new ApiResponseCustomersData().items(custInfoList)));
    }
}
